/**
 * 力扣2:两数相加
 */


class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //定义头节点
        ListNode head = null;
        ListNode next = null;
        int cur = 0;
        while(l1 != null || l2 != null){
            //一个节点一个节点地使用
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + cur;

            //传入第一个节点的值
            if(head == null){
                //sum%10的原因是节点只接受 个位数
                head = new ListNode(sum%10);
                next = head;
            }else{
                //传入后续的值
                next.next = new ListNode(sum%10);
                next = next.next;
            }
            //当sum的值超过10后需要再增加一个节点来存十位数的值
            cur = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if(cur > 0){
            next.next = new ListNode(cur);
        }
        return head;
    }
}